/**
 * 
 */
package cc.monggo.web.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cc.monggo.web.filter.response.PrintWriterResponseWrapper;

/**
 * @author fangjinsong
 * 
 */
public class PrintWriteFilterDemo implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		final HttpServletRequest httpRequest = (HttpServletRequest) req;
		final HttpServletResponse httpResponse = (HttpServletResponse) resp;
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		PrintWriterResponseWrapper wrapper = new PrintWriterResponseWrapper(
				httpResponse,buffer);
		chain.doFilter(httpRequest, wrapper);
		wrapper.flushBuffer();
		String originalData = new String(buffer.toByteArray());
		String updatedData = originalData.replaceAll("12", "13");
		
		byte[] updataDatas = updatedData.getBytes(); 
		
		OutputStream out = httpResponse.getOutputStream();
		String json = "{content:'SUCCESS'}";
		updataDatas = json.getBytes();
		out.write(updataDatas);
		out.flush();
		out.close();
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
